package com.lrd.snapshotorder.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lrd.snapshotorder.entity.RecipientAddress;
import com.lrd.snapshotorder.mapper.RecipientAddressMapper;
import com.lrd.snapshotorder.protocol.ResultData;
import com.lrd.snapshotorder.protocol.dto.address.RecipientAddressListDto;
import com.lrd.snapshotorder.protocol.dto.address.RecipientAddressQueryDto;
import com.lrd.snapshotorder.protocol.dto.address.RecipientAddressSaveDto;
import com.lrd.snapshotorder.service.RecipientAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class RecipientAddressServiceImpl implements RecipientAddressService {

    @Autowired
    private RecipientAddressMapper recipientAddressMapper;

    @Override
    public ResultData<List<RecipientAddressListDto>> queryRecipientAddressList(RecipientAddressQueryDto dto) {
        log.info("查询收货人地址，param={}", JSONUtil.toJsonStr(dto));
        Page<RecipientAddress> recipientAddressPage = recipientAddressMapper.queryRecipientAddressList(dto);
        if (CollUtil.isEmpty(recipientAddressPage.getRecords())) {
            return new ResultData<>(0, "收货人地址列表为空", new ArrayList<>(), 0L);
        }
        List<RecipientAddressListDto> recipientAddressListDtos = BeanUtil.copyToList(recipientAddressPage.getRecords(), RecipientAddressListDto.class);
        return new ResultData<>(0, "", recipientAddressListDtos, recipientAddressPage.getTotal());
    }

    @Override
    public ResultData<Boolean> saveRecipientAddress(RecipientAddressSaveDto dto) {
        RecipientAddress recipientAddress = BeanUtil.toBean(dto, RecipientAddress.class);
        if (recipientAddress.getId() != null) {
            recipientAddressMapper.updateById(recipientAddress);
        } else {
            recipientAddressMapper.insert(recipientAddress);
        }
        return ResultData.success(true);
    }

    @Override
    public ResultData<Boolean> setRecipientAddressStatus(Integer id) {
        RecipientAddress recipientAddress = recipientAddressMapper.selectById(id);
        recipientAddress.setStatus(1 - recipientAddress.getStatus());
        recipientAddressMapper.updateById(recipientAddress);
        return ResultData.success(true);
    }
}
